package com.anysoft.register;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ToastUtils;
import com.anysoft.HostConstant;
import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.UploadIdCardBean;
import com.anysoft.event.RegisterSuccessEvent;
import com.anysoft.linstener.OnNextLinstener;
import com.anysoft.login.LoginActivity;
import com.anysoft.me.callback.StringDialogCallback;
import com.anysoft.me.utils.PermissionManager;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.DateTimeUtils;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.IcbcClickableSpan;
import com.anysoft.utils.StringUtils;
import com.anysoft.view.CustomImagView;
import com.anysoft.view.CustomMarqueeTextView;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by lty on 2017/11/17.
 * 注册页面
 */

public class RegisterStep1_1Activity extends BaseActivity implements View.OnClickListener, PermissionManager.OnPermissionListener {

    @BindView(R.id.leftButton)
    Button leftButton;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.rightButton)
    Button rightButton;
    @BindView(R.id.titlebar)
    FrameLayout titlebar;
    @BindView(R.id.iv_leftButton)
    ImageView ivLeftButton;
    @BindView(R.id.cmtv_title)
    CustomMarqueeTextView cmtvTitle;
    @BindView(R.id.civ_register_idcard_front)
    CustomImagView civRegisterIdcardFront;
    @BindView(R.id.rl_register_idcard_front_container)
    RelativeLayout rl_register_idcard_front_container;
    @BindView(R.id.rl_register_idcard_reverse_container)
    RelativeLayout rl_register_idcard_reverse_container;
    @BindView(R.id.rl_container1)
    RelativeLayout rl_container1;
    @BindView(R.id.iv_idcard_front)
    ImageView iv_idcard_front;
    @BindView(R.id.iv_idcard_reverse)
    ImageView iv_idcard_reverse;

    @BindView(R.id.civ_register_idcard_reverse)
    CustomImagView civRegisterIdcardReverse;
    @BindView(R.id.tv_register_desc)
    TextView tvRegisterDesc;
    @BindView(R.id.cb_register_choice)
    CheckBox cbRegisterChoice;
    @BindView(R.id.tv_register_tips)
    TextView tvRegisterTips;
    @BindView(R.id.btn_register_next)
    Button btnRegisterNext;
    private int idcard_flag = -1;
    private Dialog dialog;
    private String selectPath;
    private String name, id_number, address, id_time;
    private boolean front_success = false;
    private boolean reverse_success = false;
    private String frontPagePath;
    private String reversePagePath;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_register_step1_1);
        ButterKnife.bind(this);
        title.setText("开户");

        setOnNextLinstener(new OnNextLinstener() {
            @Override
            public void OnCancelNext() { //正确
                uploadIdCardImag();
            }

            @Override
            public void OnConfirmNext() { //有误修改
                ActivityUtils.gotoRegisterStep1_2Activity(RegisterStep1_1Activity.this, name, id_number, address, id_time,
                        "toIdCard");
            }

            @Override
            public void OndoConfirm() {
                startActivity(new Intent().setClass(RegisterStep1_1Activity.this, LoginActivity.class));
                finish();
            }
        });
        initTips();
        setIdCardFrontContainerUI(false);
        setIdCardReverseContainerUI(false);
        initIdcardContainer(1.6f, rl_register_idcard_front_container, 240);
        initIdcardContainer(1.6f, civRegisterIdcardFront, 240);
        initIdcardContainer(1.6f, rl_register_idcard_reverse_container, 240);
        initIdcardContainer(1.6f, civRegisterIdcardReverse, 240);
        initIdcardContainer(1.6f, iv_idcard_front, 440);
        initIdcardContainer(1.6f, iv_idcard_reverse, 440);
    }

    /**
     * 动态设置身份证照片容器宽高比
     */
    private void initIdcardContainer(float rate, View view, int diffValue) {
        int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
//        float rate =  1.6f; //192/113
        int idcradWidth = screenWidth - diffValue;
        int idcardHeight = (int) (idcradWidth / rate);
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        layoutParams.width = idcradWidth;
        layoutParams.height = idcardHeight;
        view.setLayoutParams(layoutParams);
    }

    /**
     * 初始化提示协议
     */
    private void initTips() {
        String tip1 = "《电子交易服务协议》";
        String tip2 = "《证券投资基金投资人权益须知》";
        String tip3 = "《基金直销货币基金快速赎回业务协议》";
        SpannableString spantip1 = new SpannableString(tip1);
        SpannableString spantip2 = new SpannableString(tip2);
        SpannableString spantip3 = new SpannableString(tip3);
        ClickableSpan clicktip1 = new IcbcClickableSpan(tip1, this, 1);
        ClickableSpan clicktip2 = new IcbcClickableSpan(tip2, this, 2);
        ClickableSpan clicktip3 = new IcbcClickableSpan(tip3, this, 3);
        spantip1.setSpan(clicktip1, 0, tip1.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spantip2.setSpan(clicktip2, 0, tip2.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spantip3.setSpan(clicktip3, 0, tip3.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tvRegisterTips.setText("请阅读并同意以下协议");
        tvRegisterTips.append(spantip1);
        tvRegisterTips.append(spantip2);
        tvRegisterTips.append(spantip3);
        tvRegisterTips.setMovementMethod(LinkMovementMethod.getInstance());

        tvRegisterTips.setLongClickable(false);
        tvRegisterTips.setHighlightColor(getResources().getColor(android.R.color.transparent));

        String registerDesc = "非中国大陆地区居民或识别不成功, 需要<font color='#6497ed'>手动填写注册</font>";
        tvRegisterDesc.setText(Html.fromHtml(registerDesc));
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private int recogType = 0;

    @OnClick({R.id.civ_register_idcard_front, R.id.civ_register_idcard_reverse,
            R.id.rl_register_idcard_front_container, R.id.rl_register_idcard_reverse_container,
            R.id.cb_register_choice,
            R.id.btn_register_next, R.id.leftButton})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.leftButton:
                finish();
                break;
            case R.id.rl_register_idcard_front_container:
            case R.id.civ_register_idcard_front:
                idcard_flag = 1;
                showSelectTypeDialog();
                break;
            case R.id.rl_register_idcard_reverse_container:
            case R.id.civ_register_idcard_reverse:
                idcard_flag = 2;
                showSelectTypeDialog();
                break;
            case R.id.cb_register_choice: //勾选注意信息
                break;
            case R.id.btn_register_next:
                if (!cbRegisterChoice.isChecked()) {
                    showConfirmAlert(mActivity, "请阅读并同意协议");
                    return;
                }
                //提示校验扫描结果
                if (front_success && reverse_success) {
                    showConfirmAlert(this, "扫描信息确认", "姓名：" + name
                            + "\n身份证: " + id_number, "有误,去修改", "正确");
                } else {
                    showConfirmAlert(this, "未扫描完成");
                }
                break;
            case R.id.tv_ocr_identity:
                dialog.dismiss();
                recogType = 1;
                requestIdentityPermissions();
                break;
            case R.id.tv_photo_choice:
                dialog.dismiss();
                recogType = 2;
                requestIdentityPermissions();
                break;
            case R.id.ll_upload_cancel:
                dialog.dismiss();
                break;
        }
    }

    private void requestIdentityPermissions() {
        if (PermissionManager.getInstance().checkPermissions(this, PermissionManager.PERMISSION_READ_WEITE_CAMERA)) {
            if (recogType == 1) {
                //有授权，直接开启摄像头
                ActivityUtils.openCameraActivity(this, idcard_flag);
            } else {
                ActivityUtils.openLocalPick(this);
            }
        } else {
            PermissionManager.getInstance().requestPermissions(this, PermissionManager.REQUEST_READ_WEITE_CAMERA,
                    PermissionManager.PERMISSION_READ_WEITE_CAMERA, this);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onPermissionSuccess() {
        if (recogType == 1) {
            //有授权，直接开启摄像头
            ActivityUtils.openCameraActivity(this, idcard_flag);
        } else {
            ActivityUtils.openLocalPick(this);
        }
    }

    @Override
    public void onPermissionFail() {
        ToastUtils.showShort("请求权限失败,请重试");
    }


    public void setIdCardFrontContainerUI(boolean visible) {
        if (visible) {
            civRegisterIdcardFront.setVisibility(View.VISIBLE);
            rl_register_idcard_front_container.setVisibility(View.GONE);
        } else {
            rl_register_idcard_front_container.setVisibility(View.VISIBLE);
            civRegisterIdcardFront.setVisibility(View.GONE);
        }
    }

    public void setIdCardReverseContainerUI(boolean visible) {
        if (visible) {
            civRegisterIdcardReverse.setVisibility(View.VISIBLE);
            rl_register_idcard_reverse_container.setVisibility(View.GONE);
        } else {
            rl_register_idcard_reverse_container.setVisibility(View.VISIBLE);
            civRegisterIdcardReverse.setVisibility(View.GONE);
        }
    }

    /**
     * 上传身份证正反面
     */
    private void uploadIdCardImag() {
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(id_number)) {
            return;
        }
        File file1 = new File(frontPagePath);
        String name1 = file1.getName();
        File file2 = new File(reversePagePath);
        String name2 = file2.getName();
        Log.e(TAG, "upLoad: " + name1 + " === " + name2);
        if (!file1.exists() || !file2.exists()) {
            Toast.makeText(this, "文件不存在，请修改文件路径", Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("clientType", HostConstant.CLIENT_TYPE);//客户端类型
        params.put("fileType", "1");
        params.put("certificateNo", id_number);
        params.put("certificateType", "0");
        params.put("operationType", "1"); //开户 1  大额交易 2  忘记密码 3
        OkGo.<String>post(HostConstant.UPLOAD_IMAGE)
                .tag(this)
                .isMultipart(true)
                .params(HttpUtils.getCommonParams(this, params))
                .params("file1", file1)
                .params("file2", file2)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        updateUploadUI(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void updateUploadUI(String json) {
        UploadIdCardBean uploadIdCardBean;
        try {
            uploadIdCardBean = new Gson().fromJson(json, UploadIdCardBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            return;
        }

        if (uploadIdCardBean == null || uploadIdCardBean.getErrorCode() == null) {
            showConfirmAlert(mActivity, "提示", getString(R.string.no_data));
            return;
        }

        if ("ACCOUNT_OPENING_ERROR".equals(uploadIdCardBean.getErrorCode())) {
            showConfirmAlertWithLinstener(RegisterStep1_1Activity.this, "提示", uploadIdCardBean.getErrorMessage(), "确定");
        } else if ("0000".equals(uploadIdCardBean.getErrorCode())) {
            ActivityUtils.gotoRegisterStep1_2Activity(RegisterStep1_1Activity.this, name, id_number, address, id_time,
                    "toBank");
        } else {
            showConfirmAlert(RegisterStep1_1Activity.this, "上传失败");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    }

    /**
     * 识别成功后设置身份证正反面的图片
     *
     * @param cutPagePath
     * @param recogResult
     */
    private void setIdCardImage(String cutPagePath, String recogResult) {
        if (!TextUtils.isEmpty(cutPagePath) && !TextUtils.isEmpty(recogResult)) {
            processScanResult(recogResult);
            if (idcard_flag == 1) {
                if (recogResult.contains("公民身份号码")) {
                    if (resultMap != null) {
                        name = resultMap.get("姓名");
                        id_number = resultMap.get("公民身份号码");
                        String str = resultMap.get("住址");
                        address = str.substring(str.indexOf("市") + 1);
                    }

                    if (!TextUtils.isEmpty(id_number)) {
                        if (!StringUtils.isIdentity(id_number)) {
                            showConfirmAlert(this, "证件号码格式不合规");
                            setIdCardFrontContainerUI(false);
                            front_success = false;
                            return;
                        }
                        if (id_number.startsWith("X")) {
                            showConfirmAlert(this, "请按照提示要求上传证件");
                            setIdCardFrontContainerUI(false);
                            front_success = false;
                            return;
                        } else {
                            setIdCardFrontContainerUI(true);
                            civRegisterIdcardFront.setImageBitmap(BitmapFactory.decodeFile(cutPagePath));
                            front_success = true;
                        }
                    } else {
                        showConfirmAlert(this, "请按照提示要求上传证件");
                        setIdCardFrontContainerUI(false);
                        front_success = false;
                        return;
                    }
                    frontPagePath = cutPagePath;
                } else {
                    showConfirmAlert(this, "请按照提示要求上传证件");
                    setIdCardFrontContainerUI(false);
                    front_success = false;
                    return;
                }
            }
            if (idcard_flag == 2) {
                if (recogResult.contains("有效期至")) {
                    if (resultMap != null) {
                        id_time = resultMap.get("有效期至");
                    }
                    if (!StringUtils.isNullOrEmpty(id_time)) {
                        if (id_time.contains("长期")) {
                            setIdCardReverseContainerUI(true);
                            civRegisterIdcardReverse.setImageBitmap(BitmapFactory.decodeFile(cutPagePath));
                            reversePagePath = cutPagePath;
                            reverse_success = true;
                        } else if (DateTimeUtils.isValidDate(id_time)) {
                            setIdCardReverseContainerUI(true);
                            civRegisterIdcardReverse.setImageBitmap(BitmapFactory.decodeFile(cutPagePath));
                            reversePagePath = cutPagePath;
                            reverse_success = true;
                        } else {
                            showConfirmAlert(this, "证件有效期日期格式不合规");
                            setIdCardReverseContainerUI(false);
                            reverse_success = false;
                            return;
                        }
                    } else {
                        showConfirmAlert(this, "请按照提示要求上传图片");
                        setIdCardReverseContainerUI(false);
                        reverse_success = false;
                        return;
                    }
                } else {
                    showConfirmAlert(this, "请按照提示要求上传图片");
                    setIdCardReverseContainerUI(false);
                    reverse_success = false;
                    return;
                }
            }
        }
    }

    private Map<String, String> resultMap = new HashMap<>();

    /**
     * 处理扫描结果
     *
     * @param recogResult
     */

    private void processScanResult(String recogResult) {
        if (recogResult != null) {
            String[] strings = recogResult.split(",");
            for (int i = 0; i < strings.length; i++) {
                String[] split = strings[i].split(":");
                for (int j = 0; j < split.length; j++) {
                    String key = split[0];
                    String value = "";
                    if (!TextUtils.isEmpty(split[1])) {
                        value = split[1];
                    }
                    resultMap.put(key, value);
                }

            }
            Log.e("lty", "注册页面 最后结果: " + resultMap.toString());
        }
    }

    /**
     * 展示弹框,从相册/照相选择
     */
    private void showSelectTypeDialog() {
        dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_upload_identity_layout, null);
        //初始化控件
        TextView tv_ocr_identity = (TextView) inflate.findViewById(R.id.tv_ocr_identity);
        TextView tv_photo_choice = (TextView) inflate.findViewById(R.id.tv_photo_choice);
        LinearLayout ll_upload_cancel = (LinearLayout) inflate.findViewById(R.id.ll_upload_cancel);
        tv_ocr_identity.setOnClickListener(this);
        tv_photo_choice.setOnClickListener(this);
        ll_upload_cancel.setOnClickListener(this);
        //将布局设置给Dialog
        dialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = dialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = getResources().getDisplayMetrics().widthPixels;
        dialogWindow.setAttributes(lp);
        dialog.show();
    }

    /***
     * @param @param context @param @param uri @param @return 设定文件 @return
     *               String 返回类型 @throws
     * @Title: getPath
     * @Description: 获取图片路径
     */

    public static String getPath(Context context, Uri uri) {
        if ("content".equalsIgnoreCase(uri.getScheme())) { // 忽略大小写
            // String[] projection = { "_data" };
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, null, null,
                        null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGestureSetCallBack(RegisterSuccessEvent event) {
        if (event.isSuccess) {
            finish();
        }
    }
}
